package com.lb.uts.client.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

/**
 * 脚本的执行工具
 * user:Administrator
 * date:2020/5/17 21:04
 */
public class ScriptUtil {

    private static final Logger logger = LoggerFactory.getLogger(ScriptUtil.class);

    /**
     * 脚本的执行
     *
     * @param scriptType 脚本类型
     * @param scriptPath 脚本路径
     */
    public static void exeScript(Integer scriptType, String scriptPath) throws Exception{
        logger.info("开始执行脚本,脚本类型：{}，脚本路径:{}", scriptType, scriptPath);
        switch (scriptType) {
            case 1:
                exeShellScriptSimple(scriptPath);
                break;
            default:
                logger.error("不支持的脚本的类型");
        }
    }

    /**
     * 简单粗暴的执行shell脚本
     * <p>可能的错误：没权限运行</p>
     *
     * @param scriptPath
     */
    private static void exeShellScriptSimple(String scriptPath) throws Exception {
        Process p = Runtime.getRuntime().exec(scriptPath);
        p.waitFor();
    }

    /**
     * 打印shell的具体运行状态进行log出来
     * @param scriptPath
     * @throws Exception
     */
    private static void exeShellScript(String scriptPath) throws Exception {
        ProcessBuilder pb = new ProcessBuilder(scriptPath);
        int runningStatus = 0;
        String s = null;
        Process p = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((s = stdInput.readLine()) != null) {
            logger.error("执行脚本失败:{}",s);
        }
        while ((s = stdError.readLine()) != null) {
            logger.error("执行脚本失败:{}",s);
        }
        p.waitFor();
    }
}
